package com.kimho.core;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kimho.util.Util;

public class SessionFilter implements Filter{
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)res;
		String isAjax = request.getHeader("x-requested-with");
		if(!Util.isEmpty(isAjax) && isAjax.equalsIgnoreCase("XMLHttpRequest")){
			if(request.getParameter("login")!=null && request.getParameter("login").equals("login") || request.getServletPath().endsWith("user/login")){
				chain.doFilter(request, response);//不拦截登陆页面的地点选择和登陆的异步请求
				return;
			}else if(request.getSession()==null || request.getSession().getAttribute("user")==null){
				response.addHeader("sessionstatus", "timeout");//拦截异步请求,发送错误码,js进行处理
				return;
			}
		}//不拦截非异步请求
		chain.doFilter(request, response);
		return;
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
	}

}
